<?php
/*
 * Created on 2012年11月16日11:00:26
 * @author yxt
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
include_once dirname(__FILE__).DIRECTORY_SEPARATOR .'topic_item.class.php';
//$GLOBALS['obj'][]=new nl_topic_item_image();
/**
 * 信息包组合业务
 */

class nl_topic_item_image{
/**明sql执行情况用于调试
 * 需要在nl_common.func.php中执行sql的地方加入
    $b=$q===false?"<font color=red>执行失败</font>":"执行成功：";
	$sql_arr[]=$b.$sql;
 */

static public $sql_arr=array();
//当前调用方法产生的sql语句,一个方法可能有多个sql
	const CACHE_TIME_OUT = 300;
	//排序规则
 static public $order=
 array(
NL_ORDER_NUM_ASC=>" order by  nns_order asc ",
NL_ORDER_NUM_DESC=>" order by  nns_order desc ",
NL_ORDER_TIME_ASC=>" order by  nns_create_time asc ",
NL_ORDER_TIME_DESC=>" order by  nns_create_time desc ",
 );
 	/**
	 * 构造 INSERT sql语句
	 * @param array $params  插入数据格式：字段名=>字段值
	 * @param string $table_name 表名字
	 */
	static private function _set_insert_sql($params, $table_name) {
		$ins_sql = 'INSERT INTO `' . $table_name . '` (';
		foreach ($params as $key => $val) {
			//yxt一下一行是对所有的html实体标签和单双引号进行转义
			$val = htmlentities($val, ENT_QUOTES, "UTF-8");
			$ins_key[] = 'nns_'.$key;
			$ins_val[] = '\'' . $val . '\'';
		}
		$ins_sql .= implode(',', $ins_key) . ') VALUES(' . implode(',', $ins_val) . ')';
		return $ins_sql;
	}
	/**
	 *从dc模块获取信息相册图片列表数量
	 * @param object $dc dc模块
	 * @param string $id 信息id
	 * @return *
	 * 			FALSE 查询失败
	 * 			int  查询数量
	 */
  	static function count_topic_item_image_list ($dc, $id){
		$sql="select count(1) as c from nns_topic_item_images where nns_topic_item_id='{$id}'";
		$r=nl_query_by_db($sql,$dc->db());
		if($r===true) return 0;
		if($r===false) return false;
		return $r[0]['c'];
  	}
  	/**
	 *从DC模块获取信息相册图片列表
	 * @param dc DC模块
	 * @param string 信息ID
     * @param int 起始查询记录位置
	 * @param int 查询记录条数
	 * @param string 排序规则，
	* @param String 读取策略
	* @param array $fields:需要获取的字段一维数组，注意传入的是完整的字段名，也就是需要nns前缀
	 * @return *
	 * 			Array 信息包内容列表结果
	 * 			FALSE 查询失败
	 * 			TRUE  查询成功，但无数据
	 */
  	static function get_topic_item_image_list ($dc,$item_id,$since,$num, $order=NL_ORDER_NUM_DESC,$policy=NL_DC_AUTO,$fields=array()){
		switch($policy){
			case NL_DC_DB: $result=self::_get_topic_item_image_list_db($dc,$item_id,$since,$num, $order,$fields); break;
			case NL_DC_CACHE: $result=self::_get_imgcache_by_item_id($dc,$item_id,$since,$num,$fields,$order,$policy); break;
			case NL_DC_AUTO: $result=self::_get_imgcache_by_item_id($dc,$item_id,$since,$num,$fields,$order,$policy); break;
		}
		return $result;
  	}
  	/**
  	 * 从数据库直接获取信息相册图片列表
  	 */
	static private function _get_topic_item_image_list_db($dc,$item_id,$since=null,$num, $order=NL_ORDER_NUM_DESC,$fields=array()){
		if(empty($fields)){
			$field="*";
		}else{
			$field=implode(',',$fields);
		}
		if($since===null){
 		$limit="";
	 	}else{
	 		$limit=" limit {$since},{$num}";
	 	}
		$sql="select {$field} from nns_topic_item_images where nns_topic_item_id='{$item_id}' ".self::$order[$order]." {$limit}";
		$result=nl_query_by_db($sql,$dc->db());
		return $result;
	}
  	/**
  	 *从dc模块添加一条相册图片
  	 *@param object $dc dc模块
  	 *@param array  $params 相册内容数据
  	 *       array(
  	 * 			'image'=>'相册图片地址',
  	 * 			'summary'=>'相册图片描述',
  	 * 			'topic_item_id'=>'相册图片所属信息id',
  	 * 		 )
  	 */
  	static function add_topic_item_image($dc,$topic_id,$params){
  		$db=$dc->db();
		//先获取当前记录总数
		$sql="select max(nns_order) as c from nns_topic_item_images where nns_topic_item_id='{$topic_id}'";
		$r=nl_query_by_db($sql,$db);
		$order_num=(empty($r[0]['c'])&&$r[0]['c']!=='0')?0:$r[0]['c']+1;
		$params['order']=$order_num;
		$params['topic_item_id']=$topic_id;
		$params['create_time']=date('Y-m-d H:i:s');
		$id = np_guid_rand();
		$params['id']=$id;
		$sql=self::_set_insert_sql($params, "nns_topic_item_images");
		$result=nl_execute_by_db($sql,$db);
		return $result===false?false:$id;
  	}

  	/**
  	 *从dc模块删除一条相册图片
  	 *@param object $dc dc模块
  	 *@param string $id 图片id
  	 */
  	static function delete_topic_item_image($dc,$id){
  		$db=$dc->db();
		//第一步删除所属信息的缓存
		//获取图片所属信息id
		$sql="select nns_topic_item_id from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_query_by_db($sql,$db);
		self::_del_cache_by_item_id($dc,$result[0]['nns_topic_item_id']);
		//第二步删除图片
		$sql="delete from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_execute_by_db($sql,$db);
		return $result;
  	}

  	/**
	 * 从DC模块排序当前信息相册图片到最前
	 * @param dc DC模块
     * @param string 图片ID
	 * @return *
	 * 			FALSE 排序失败
	 * 			TRUE  排序成功
	 */
	static function update_topic_item_image_to_order_first ($dc,$id){
		$db=$dc->db();
		$cache=$dc->cache();
		//获取图片所属信息id和order
		$sql="select nns_topic_item_id,nns_order from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_query_by_db($sql,$db);
		$topic_item_id=$result[0]['nns_topic_item_id'];
		$order=$result[0]['nns_order'];
		//判断图片是否已经处于最顶级，如果是则返回false
		$sql="select * from nns_topic_item_images where nns_order>{$order} and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		if($result===false || $result===true){
			return false;
		}
		//删除当前所属信息缓存
		self::_del_cache_by_item_id($dc,$topic_item_id);
		//将所有比当前图片order大的order-1
		$sql="update nns_topic_item_images set nns_order=nns_order-1 where nns_order>{$order} and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		//将当前的order=count(1)
		$sql="select max(nns_order) as c from nns_topic_item_images";
		$result=nl_query_by_db($sql,$db);
		$sql="update nns_topic_item_images set nns_order=".($result[0]['c']+1)." where nns_id='{$id}' and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		return $result;
  	}

	/**
	 * 从DC模块排序当前信息到最末
	 * @param dc DC模块
     * @param string 图片ID
	 * @return *
	 * 			FALSE 排序失败
	 * 			TRUE  排序成功
	 */
  	static function update_topic_item_image_to_order_last ($dc,$id){
		$db=$dc->db();
		//获取图片所属信息id和order
		$sql="select nns_topic_item_id,nns_order from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_query_by_db($sql,$db);
		$topic_item_id=$result[0]['nns_topic_item_id'];
		$order=$result[0]['nns_order'];
		//判断图片是否已经处于最顶级，如果是则返回false
		$sql="select * from nns_topic_item_images where nns_order<{$order} and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		if($result===false || $result===true){
			return false;
		}
		//删除当前所属信息缓存
		self::_del_cache_by_item_id($dc,$topic_item_id);
		//将所有比当前图片order小的order+1
		$sql="update nns_topic_item_images set nns_order=nns_order+1 where nns_order<{$order} and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		//将当前的order=0
		$sql="update nns_topic_item_images set nns_order=0 where nns_id='{$id}' and nns_topic_item_id='{$topic_item_id}'";
		$result=nl_query_by_db($sql,$db);
		return $result;
  	}

  	/**
	 * 从DC模块对调2条信息的排序
	 * @param dc DC模块
     * @param string 当前图片ID
	 * @param string 对调图片ID
	 * @return *
	 * 			FALSE 排序失败
	 * 			TRUE  排序成功
	 */
   	static function update_topic_item_image_order_switch ($dc,$id,$other_id){
		$db=$dc->db();
		//获取源图片的order
		$sql="select nns_order from nns_topic_item_images where nns_id='{$id}'";
		$r1=nl_query_by_db($sql,$db);
		//获取目标图片所属信息id和order
		$sql="select nns_topic_item_id,nns_order from nns_topic_item_images where nns_id='{$other_id}'";
		$r2=nl_query_by_db($sql,$db);
		//删除当前所属信息缓存
		self::_del_cache_by_item_id($dc,$r2[0]['nns_topic_item_id']);
		//互换order
		$sql="update nns_topic_item_images set nns_order={$r2[0]['nns_order']} where nns_id='{$id}'";
		$r3=nl_execute_by_db($sql,$db);
		$sql="update nns_topic_item_images set nns_order={$r1[0]['nns_order']} where nns_id='{$other_id}'";
		$r4=nl_execute_by_db($sql,$db);
		return $r1&&$r2&&$r3&&$r4;
   	}

/**
 * 设置信息指定条件的相册缓存
 * @param dc $dc
 * @param string $topic_item_id：所属信息id
 * @param int $since：起始位置
 * @param int $num：获取长度
 * @param string $order：排序规则
 * @return bool
 */
 static private function _set_imgcache_by_item_id($dc,$topic_item_id,$since=null,$num,$order=NL_ORDER_NUM_DESC){
 	if(!$dc->is_cache_enabled()) return null;
 	if($since===null){
 		$limit="";
 	}else{
 		$limit=" limit {$since},{$num} ";
 	}
	$sql="select * from nns_topic_item_images where nns_topic_item_id='{$topic_item_id}' ".self::$order[$order]." {$limit}";
	$r=nl_query_by_db($sql,$dc->db());
	if($r!==false){
		//生成key
		$key=time();
		//保存key
		$dc->cache()->set("topic_item_image_".$topic_item_id,$key,self::CACHE_TIME_OUT);
		$sql_md5=md5($sql);
		//设置缓存
		$dc->cache()->set('topic_item_image_'.$key.$sql_md5,$r,self::CACHE_TIME_OUT);
		return true;
	}
	return false;
 }
/**
 * 获取信息指定条件的相册缓存
 * @param dc $dc
 * @param string $topic_item_id：所属信息id
 * @param int $since：起始位置
 * @param int $num：获取长度
 * @param array $fields:需要获取的字段一维数组，为空则全部返回,需要nns前缀
 * @param string $order：排序规则
 * @param string $policy 	调用策略
 * @return bool false:说明sql语句不对
 * @return bool true:查询没有结果
 * @return array 结果二维数组
 */
 static private function _get_imgcache_by_item_id ($dc,$topic_item_id,$since=null,$num,$fields=array(),$order=NL_ORDER_NUM_DESC,$policy = NL_DC_AUTO){
	$db=$dc->db();
	if($since===null){
 		$limit="";
 	}else{
 		$limit=" limit {$since},{$num}";
 	}
	$sql="select * from nns_topic_item_images where nns_topic_item_id='{$topic_item_id}' ".self::$order[$order]." {$limit}";
	$sql_md5=md5($sql);
	if($dc->is_cache_enabled()){//如果缓存打开
		$cache=$dc->cache();
		//获取key
		$key=$cache->get("topic_time_image_".$topic_item_id);
		$r=$cache->get('topic_item_image_'.$key.$sql_md5);
		//如果没有获取到缓存，并且策略是NL_DC_AUTO的话就需要从数据库里去获取数据，并且存入缓存
		if(empty($r)&&$policy==NL_DC_AUTO){//如果获取失败，并且需要从数据库获取
			$r=nl_query_by_db($sql,$db);
			if($r!==false){
				//生成key
				$key=time();
				//保存key
				$dc->cache()->set("topic_time_image_".$topic_item_id,$key);
				$sql_md5=md5($sql);
				$dc->cache()->set('topic_item_image_'.$key.$sql_md5,$r,self::CACHE_TIME_OUT);
			}else{
				return false;
			}
		}else{//缓存获取失败，不需要从数据库获取
			return null;
		}
	}else if($policy==NL_DC_AUTO){//如果缓存关闭，并且需要从数据库获取
		$r=nl_query_by_db($sql,$db);
	}
	//如果指定了需要返回那些字段则返回指定的字段数据
	if(!empty($fields)){
		$result=array();
		$i=0;
		if(is_array($r)){
			foreach($r as $val){
				foreach($fields as $field){
					$result[$i][$field]=$val[$field];
				}
			$i++;
			}
		}else{
			$result=null;
		}
		return $result;
	}
	return $r;
}
/**
	 * 上移，先判断是否已经到达了最上面，如果已经是最上面了就不在移动
	 * 如果上面还有图片，则将当前order+1,上面一个的order-1
	 * @param DC $dc
	 * @param string $id
	 * @return -1 已经处于最高层
	 * 					0执行失败
	 *   				1执行成功
	 */
	 static public function img_up($dc,$id){
		 $db=$dc->db();
		 //获取图片所属信息id和order
		$sql="select nns_topic_item_id,nns_order from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_query_by_db($sql,$db);
		$topic_item_id=$result[0]['nns_topic_item_id'];
		$order=$result[0]['nns_order'];
		//判断是否有比当前order大的
		$sql="select nns_id from nns_topic_item_images where nns_order={$order}+1 and nns_topic_item_id='{$topic_item_id}'";
		$r=nl_query_by_db($sql,$db);
		if($r===true){
			return -1;
		}elseif($r===false){
			return 0;
		}
		$r=self::update_topic_item_image_order_switch ($dc,$id,$r[0]['nns_id']);
		if($r===false){
			return 0;
		}
		return 1;
	 }
	 /**
	  * 下移，先判断当前的图片是否已经是处于最底层了，如果是，则不做操作
	  * 如果下面还有记录，则将当前的order-1，下一个的order+1
	  * @param DC $dc
	  * @param string $id
	  * @return -1 已经处于最低层
	 * 					0执行失败
	 *   				1执行成功
	  */
	  static public function img_down($dc,$id){
		$db=$dc->db();
		//获取图片所属信息id和order
		$sql="select nns_topic_item_id,nns_order from nns_topic_item_images where nns_id='{$id}'";
		$result=nl_query_by_db($sql,$db);
		$topic_item_id=$result[0]['nns_topic_item_id'];
		$order=$result[0]['nns_order'];
		//判断是否有比当前order小的
		$sql="select nns_id from nns_topic_item_images where nns_order={$order}-1 and nns_topic_item_id='{$topic_item_id}'";
		$r=nl_query_by_db($sql,$db);
		if($r===true){
			return -1;
		}elseif($r===false){
			return 0;
		}
		$r=self::update_topic_item_image_order_switch($dc, $id, $r[0]['nns_id']);
		if($r===false){
			return 0;
		}
		return 1;
	 }
	 /**
	  * 修改图片的描述信息
	  * @param DC $dc
	  * @param string	$nns_id图片id
	  * @param string	$nns_summary
	  */
	  static public function modify_summary($dc,$nns_id,$nns_summary){
		$sql="update nns_topic_item_images set nns_summary='{$nns_summary}' where nns_id='{$nns_id}'";
		if(nl_execute_by_db($sql,$dc->db())){//如果删除成功需要删除缓存
			//获取topic_item_id
			$sql="select nns_topic_item_id from nns_topic_item_images where nns_id='{$nns_id}'";
			$re=nl_query_by_db($sql,$dc->db());
			self::_del_cache_by_item_id($dc,$re[0]['nns_topic_item_id']);
			return true;
		}
		return false;
	  }
/**
 * 删除指定信息的所有相册缓存
 * @param dc $dc
 * @param string $topic_item_id
 * @return bool
 */
 static private function _del_cache_by_item_id ($dc,$topic_item_id) {
 	if(!$dc->is_cache_enabled()) return null;
	return $dc->cache()->delete("topic_item_image_".$topic_item_id);
}
 	/**
	 * 输出sql语句（当前脚本所有调用本类生成的sql语句都在这里
	 * 调试使用
	 */
 public function add_sql ($sql) {
		self::$sql_arr[]=$sql;
	}
}

?>